
package org.donald.strategy;

import org.apache.shardingsphere.api.sharding.hint.HintShardingAlgorithm;
import org.apache.shardingsphere.api.sharding.hint.HintShardingValue;

import java.util.ArrayList;
import java.util.Collection;

public class CustomDBHintShardingAlgorithm implements HintShardingAlgorithm<Long> {

    /**
     * 根据 HintShardingValue 进行分片
     *
     * @param dataSourceNames 数据源集合
     *                        在分库时值为所有分库的集合 databaseNames
     *                        分表时为对应分库中所有分表的集合 tablesNames
     * @param hintShardingValue 分片属性，包括
     *                          logicTableName 为逻辑表，
     *                          columnName 分片键（字段），hint 策略此处为空 ""
     *                          value 之前都是从 SQL 中解析出的分片键的值，现在是通过 hintManager.addTableShardingValue("product_order", 1) 参数指定
     * @return 符合条件的数据源集合
     */
    @Override
    public Collection<String> doSharding(Collection<String> dataSourceNames, HintShardingValue<Long> hintShardingValue) {
        Collection<String> result = new ArrayList<>();
        for (String tableName : dataSourceNames) {
            for (Long shardingValue : hintShardingValue.getValues()) {
                if (tableName.endsWith(String.valueOf(shardingValue % dataSourceNames.size()))) {
                    result.add(tableName);
                }
            }
        }
        return result;
    }
}